import React, { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer, ProFormText, ProTable, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, message, Image, Popconfirm } from 'antd';
import errorImage from '@/assets/error.png';
import _ from '@/assets/utils';
import HOME_API from '@/services/home';
import styled from 'styled-components';
const RightStyle = styled.div`
    .ant-pro-table-list-toolbar-right   {
  margin-right: 1100px;
}
`;
const Newest = function Newest() {
    const columns = [{
        title: '商品名称',
        dataIndex: 'configName',
        with: '20%',
    }, {
        title: "跳转连接",
        dataIndex: 'redirectUrl',
        width: '20%',
        render: (dom) => {
            return <Button type="link"
                style={{ padding: 0 }}
                onClick={() => window.open(dom)}>
                {dom}
            </Button>;
        }
    }, {
        title: '排序值',
        dataIndex: 'configRank',
        with: '10%',
    }, {
        title: '商品编号',
        dataIndex: 'goodsId',
        with: '10%',
    }, {
        title: '添加时间',
        dataIndex: 'createTime',
        with: '20%',
        render: (dom) => {
            if (!dom) return '--';
            return _.formatTime(dom, '{0}-{1}-{2}');
        }
    }, {
        title: '操作',
        render: (_, record) => {
            let { configId, configName, redirectUrl, configRank, goodsId } = record;
            return [
                <Popconfirm key="delete" title="确定要删除这条记录吗？"
                    onConfirm={() => {
                        handleRemove([configId]);
                    }}>
                    <a href="#">删除</a>
                </Popconfirm>,
                <Button key="update" type="link"
                    onClick={() => {
                        // 防止第一次加载组件，直接点击修改，如果按照异步操作，ModelForm还没有渲染解析，我们是获取不到实例信息的
                        flushSync(() => {
                            setModelVisible(true);
                            setConfigId(configId);
                        })
                        // 给Form内部的三个字段赋值
                        modelFormIns.current.setFields([{
                            name: 'configName',
                            value: configName
                        }, {
                            name: 'redirectUrl',
                            value: redirectUrl
                        }, {
                            name: 'goodsId',
                            value: goodsId
                        }, {
                            name: 'configRank',
                            value: configRank
                        }]);
                    }}>
                    修改
                </Button>
            ];
        }
    }]
    const [modelVisible, setModelVisible] = useState(false),//弹model框
    [configId, setConfigId] = useState(null),//判断新增还是修改
    [configType, setConfigType] = useState(4),
    [selectList, setSelectList] = useState([]),//存批量选中的id
    [] = useState([]),
    modelFormIns = useRef(),//清除model里数据要拿到他的dom元素
    tableIns = useRef(); //刷新页面的
/* 表格数据的处理 */
const queryTableData = async ({ pageSize, current,configType }) => {
    let tableData = [],
        total = 0;
    try {
        let { resultCode, data } = await HOME_API.newShopsList(current, pageSize,configType);
        if (+resultCode === 200) {
            total = +data.totalCount;
            tableData = data.list;
        }
    } catch (_) { }
    // 不论请求成功还是失败，都让表格进行渲染
    return {
        success: true,
        data: tableData,
        total
    };
};
/* 提交信息 */
const submit = async (values) => {
    let requestFunc = HOME_API.hotShopsInsert,
        tip = '新增';
        values.configType = configType;
    if (configId) {
        requestFunc = HOME_API.hotShopsUpdate;
        tip = '修改';
        values.configId = configId;
        values.configType = configType;
    }
    try {
        let { resultCode } = await requestFunc(values);
        if (+resultCode !== 200) {
            message.error(`很遗憾，${tip}失败了，请稍后再试~`);
            return;
        }
        message.success(`恭喜您，${tip}成功！`);
        modelOpenChange(false);
        tableIns.current.reload();
    } catch (_) { }
};
const handleRemove = async (ids) => {
    try {
        let { resultCode } = await HOME_API.hotShopsRemove(ids);
        if (+resultCode !== 200) {
            message.error('很遗憾，删除失败，请稍后再试！');
            return;
        }
        message.error('恭喜您，删除成功！');
        tableIns.current.reload();
    } catch (_) { }
};
/* Model关闭后要干什么 */
const modelOpenChange = (bool) => {
    if (bool) return;
    setModelVisible(false);
    setConfigId(null);
    modelFormIns.current.resetFields();
};
    return <PageContainer>
        <RightStyle>
 <ProTable
            request={queryTableData}
            columns={columns}
            search={false}
            options={{
                density: false,
                reload: false,
                setting: false
            }}
            pagination={{
                pageSize: 10,
                hideOnSinglePage: false,
                showTotal: false,
                showQuickJumper: false,
                showSizeChanger: false
            }}
            toolBarRender={() => {
                return [
                    <Button key="new" type="primary"
                        onClick={() => setModelVisible(true)}
                    >
                        <PlusOutlined /> 新增
                    </Button>,

                    <Button key="delete" type="primary" danger
                        onClick={async () => {
                            if (selectList.length === 0) {
                                message.warning('请至少选择一项进行删除~');
                                return;
                            }
                            await handleRemove(selectList);
                        }}
                    >
                        <MinusOutlined /> 批量删除
                    </Button>
                ];
            }}
            actionRef={tableIns}
            rowKey="configId"
            rowSelection={{
                onChange: (selectedIds) => setSelectList(selectedIds)
            }}
        />
</RightStyle>

        <ModalForm
            title={`${configId ? '修改' : '添加'}商品`}
            width="500px"
            layout='horizontal'
            open={modelVisible}
            onOpenChange={modelOpenChange}
            labelCol={{ span: 5 }}
            validateTrigger="onBlur"
            initialValues={{
                carouselUrl: '',
                carouselRank: '',
                redirectUrl: ''
            }}
            formRef={modelFormIns}
            onFinish={submit}
        >
            <ProFormText
                label="商品名称"
                name="configName"
                placeholder=""
                rules={[
                    { required: true, message: '名称不能为空' }
                ]}
            />

            <ProFormText
                label="跳转连接"
                name="redirectUrl"
                placeholder=""
            />

            <ProFormText
                label="商品编号"
                name="goodsId"
                placeholder=""
                rules={[
                    { required: true, message: '编号不能为空' }
                ]}
            />
            <ProFormText
                label="排序值"
                name="configRank"
                placeholder=""
                rules={[
                    { required: true, message: '排序不能为空' }
                ]}
            />
        </ModalForm>
    </PageContainer>;
};
export default Newest;